import React from 'react'
import { connect } from 'dva'
import {
  Tabs,
  Form,
  Row,
  Col,
  Input,
  Cascader,
  Tag,
  Icon,
  DatePicker,
  Select,
  Button,
  Upload,
  Modal,
  Divider,
  message,
  Tree
} from 'antd'
import { Link, hashHistory } from 'dva/router'
import config from 'config/config'
import {isEmpty, cloneDeep, merge,pick,get,set} from 'lodash'

import { mapStateToProps } from 'utils/view_utils'
import styles from './roleAdminDetailStyle.less'
import cx from 'classnames'

import { Grid, QueryCondition } from 'widget/Grid/index'
import { CollapsiblePanels } from 'widget/CollapsiblePanels/index'
import TreeSelect from 'widget/TreeTransfer/index'
// import menu from 'config/menu'
// import subElements from 'config/subElements'

const FormItem = Form.Item
const {TextArea} = Input
const TreeNode = Tree.TreeNode
const Option = Select.Option
const TabPane = Tabs.TabPane

const formItemLayout = {
  labelCol: {span: 4},
  wrapperCol: {span: 20},
}

// function detailSkip(type, activityId) {
//   hashHistory.push({
//       pathname: '/home/systemAdmin/roleAdminDetail',
//       query: {actionType: type, activityId}
//   });
//
// }
//  console.log('subElements',subElements)
const routeView = function ({dispatch, model, form, location}) {
  const {resetFields, getFieldDecorator, validateFields, setFieldsValue} = form
  const {modelObj, namespace} = model
  console.log('modelObj = ', modelObj)
  let {data, detailData, treeInfo,subElements,curSubElements,menu=[]} = modelObj
  let {selectedKeys,checkedKeys, halfCheckedKeys} = treeInfo
  let {actionType} = location.query
  let arrTitle = {'add': '新增角色', 'check': '角色详情', 'edit': '编辑角色'}
  
  
  //修改状态
  const changeState = (payload) => {
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {...payload}
    })
  }
  
  // -------------------tree----开始----
  //   //递归遍历树节点
  let arr=[]
  const loop = (data,prevIndex='') => data.map((item, index) => {
    let node=pick(item,['id','parentId'])
    if (item.child && item.child.length > 0) {
      return (
        <TreeNode key={item.permissionMenuId} title={item.name} node={{...node,isLeaf:false}}>
          {loop(item.child,index)}
        </TreeNode>
      )
    }else{
      let ids=`${item.parentId}.${item.permissionMenuId}`
      let idxs=`${prevIndex}.${index}`
      let isLeaf=true
      node={...node,idxs,isLeaf}
      // console.log('deepName',`${ids} ; `, `${idxs}` )
      return <TreeNode key={item.permissionMenuId}  title={item.name} node={node}/>
    }
  })
  
  function onExpandTree (expandedKeys) {
    console.log('onExpand', expandedKeys)
    treeInfo = {...treeInfo, expandedKeys, autoExpandParent: false}
    changeState({treeInfo})
  }
  
  function onCheckTree (checkedKeys,e) {
    console.log('onCheckTree', checkedKeys,e)
    treeInfo = {...treeInfo, checkedKeys,halfCheckedKeys:e.halfCheckedKeys||[],}
    changeState({treeInfo})
  }
  
  function onSelectTree (selectedKeys=[], info={}) {
    console.log('onSelectTree', selectedKeys, info)
    let {node}=get(info,`selectedNodes[0][props]`,{})
    let{isLeaf}=node
    treeInfo.isLeaf=isLeaf
    treeInfo.leafId=selectedKeys[0]||''
    curSubElements=get(subElements,`${treeInfo.leafId}`,{})
    // changeState({isLeaf})
    console.log('onSelectTree...node',node)
    treeInfo = {...treeInfo, selectedKeys}
    changeState({treeInfo,curSubElements})
  }
  
  
  function updateModel (value, name, modHierarchy) {
    let obj = modelObj
    if (modHierarchy) {
      /*modHierarchy = modHierarchy.split(".");
      modHierarchy.map(e=> {
        obj = obj[e];
      });*/
      obj[modHierarchy][name] = value
    } else {
      obj[name] = value
    }
    // 分发到model
    dispatch({
      type: `${namespace}/updateStore`,
      payload: obj
    })
  }
  
  // -------------------tree----结束-----
  // -------------------按钮资源----开始-----
  //筛选出当前资源下的按钮资源
  function modalTableData() {
    // let id = modelObj.trrOnDate
    // let getBtnList = modelObj.getBtnList || []
    // let data = []
    // getBtnList.map((item) => {
    //   if (item.parentId == id) {
    //     data.push(item)
    //   }
    // })
    // return data
    let item={}
    if(treeInfo.isLeaf&&treeInfo.leafId){
      item=get(subElements,`${selectedKeys[0]}`,{})
    }
    return item
  }
  
  let btnListColumns = [
    {title: 'UI资源名称', dataIndex: 'name', key: 'name', width: 100},
    {title: 'UI资源编号', dataIndex: 'code', key: 'code', width: 100},
    {title: 'UI资源说明', dataIndex: 'description', key: 'description',},
  ]
  
  const gridProps = {
    nameSpace: namespace,
    selectedKeysChange:'selectedKeysChange',
    data: {
      columns: btnListColumns,
      tableData:{total: '', dataSource: curSubElements.list||[]},
      selectedRowKeys:curSubElements.selectedRowKeys||[],
      pageConfig: {
        current: 1,
        pageSize: 100
      }
    },
  }
  
  // -------------------按钮资源----结束-----
  function inputChange (value, name) {
    let obj = {[name]: value}
    detailData = Object.assign(detailData, obj)
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {detailData}
    })
  }
  
  function submit () {
    validateFields(
      (err) => {
        if (!err) {
          if (detailData.name) {
            dispatch({type: `${namespace}/save`, payload: {}})
          }
        }
      },
    )
    
  }
  
  return (
    <div className={cx('pageLayout')}>
      <div className={cx('public_listMain')}>
        <div className="functionButton">
          <Button type='primary' onClick={() => {
            resetFields()
            hashHistory.push({
              pathname: MODULE_TO_ROUTES[namespace].urlArray[0],
            })
          }}>取消</Button>
          {actionType == 'add' || actionType == 'edit' ? <Button type='primary' loading={modelObj.btnLoading} onClick={e => submit(1)}>提交</Button>
            : null}
        </div>
      </div>
      
      <div>
        <CollapsiblePanels title="基本信息" hideUpDownBtn={true}>
          <Row>
            <Col className="col" span={12}>
              <FormItem {...formItemLayout}
                        label="角色名称">
                {getFieldDecorator('name', {
                  initialValue: detailData.name,
                  rules: [
                    {required: true, whitespace: true, message: '请选择角色名称'},
                    {max: 24, message: '角色名称不能超过24个字符'},
                  ],
                })(<Input
                  placeholder={'请输入角色名称'}
                  onChange={(e) => { inputChange(e.target.value, 'name') }}
                />)}
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col className="col" span={12}>
              <FormItem {...formItemLayout}
                        label="角色说明">
                {getFieldDecorator('remark', {
                  initialValue: detailData.remark,
                  rules: [
                    {required: false, whitespace: true, message: '请选择角色说明'},
                  ],
                })(<TextArea
                  placeholder={'请输入角色说明'}
                  onChange={(e) => { inputChange(e.target.value, 'remark') }}
                />)}
              </FormItem>
            </Col>
          </Row>
        </CollapsiblePanels>
        
        {/*应用及资源*/}
        <CollapsiblePanels title='关联资源' style={{position: 'relative'}}>
          <Row className={styles.ziyuanWrap} gutter={16}>
            <Col span={8} className={styles.gridConter}>
              <div  className={styles.treeBox}>
                {
                  menu && <Tree
                    checkable={true}
                    showLine={true}
                    // checkedKeys={treeInfo.checkedKeys}
                    checkedKeys={{checked: treeInfo.checkedKeys, halfChecked: treeInfo.halfCheckedKeys}}
                    // defaultExpandAll={true}
                    defaultCheckedKeys={treeInfo.checkedKeys}
                    onCheck={onCheckTree}
                    // onSelect={e => {
                    //   updateModel(e[0], 'trrOnDate')
                    // }}
                    onSelect={onSelectTree}
                  >
                    {loop(menu,0)}
                  </Tree>
                }
              </div>
            </Col>
            <Col span={16}>
              {
                treeInfo.isLeaf&& <Tabs  activeKey="1" type="card">
                  <TabPane tab="页面元素" key="1">
                    <Grid  {...gridProps}/>
                  </TabPane>
                </Tabs>
              }
            </Col>
          </Row>
        </CollapsiblePanels>
      </div>
    </div>
  )
}

// 连接视图(view)和模型(model)
export default connect(mapStateToProps)(Form.create()(routeView))
